package xyz.syyrjx.blog.service.impl;

import com.alibaba.druid.support.spring.stat.annotation.Stat;
import org.springframework.stereotype.Service;
import xyz.syyrjx.blog._enum.State;
import xyz.syyrjx.blog.dao.comment.CommentDao;
import xyz.syyrjx.blog.entity.Comment;
import xyz.syyrjx.blog.service.CommentService;

import javax.annotation.Resource;
import java.util.List;

@Service
public class CommentServiceImp implements CommentService {

    @Resource
    private CommentDao dao;

    public long countComment(){
        Comment template = new Comment();
        template.setState(State.NORMAL_STATE.getCode());
        return dao.countComment(template);
    }

    public long countCommentByBlogId(Long id) {
        Comment template = new Comment();
        template.setBlog_id(id);
        template.setState(State.NORMAL_STATE.getCode());
        return dao.countComment(template);
    }

    public void addComment(Comment comment){
        comment.setState(State.NORMAL_STATE.getCode());
        dao.insertComment(comment);
    }

    public List<Comment> queryCommentByBlogId(Long id) {
        Comment template = new Comment();
        template.setBlog_id(id);
        template.setState(State.NORMAL_STATE.getCode());
        return dao.selectComment(template);
    }

    public Comment queryCommentById(Long id){
        Comment template = new Comment();
        template.setId(id);
        template.setState(State.NORMAL_STATE.getCode());
        return dao.selectComment(template).get(0);
    }

    public void deleteCommentTree(Long id) {
        Comment template = new Comment();
        template.setId(id);
        dao.deleteComment(template);

        Comment template1 = new Comment();
        template1.setParent_comment_id(id);
        template1.setState(State.NORMAL_STATE.getCode());
        List<Comment> sonCommentList = dao.selectComment(template1);
        if (sonCommentList != null && sonCommentList.size() != 0){
            for (Comment sonComment : sonCommentList){
                deleteCommentTree(sonComment.getId());
            }
        }

        Comment template2 = new Comment();
        template2.setState(State.DELETE_STATE.getCode());
        template2.setTop_comment_id(id);
        List<Comment> grandsonCommentList = dao.selectComment(template2);
        if (grandsonCommentList != null && grandsonCommentList.size() != 0){
            for(Comment grandsonComment : grandsonCommentList){
                deleteCommentTree(grandsonComment.getId());
            }
        }
    }

    public void deleteCommentInBlog(Long id){
        Comment template = new Comment();
        template.setBlog_id(id);
        dao.deleteComment(template);
    }
}
